package com.xjc.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;

/**
 * @author:谢君臣
 * @Date:2021/6/6-16:10
 * @version:1.0
 * @function:
 */
@Configuration
@PropertySource("classpath:./jdbc.properties")
public class JdbcConfig {

    @Value("${jdbc.driverClass}")
    private  String driverClass;
    @Value("${jdbc.url}")
    private  String url;
    @Value("${jdbc.username}")
    private  String username;
    @Value("${jdbc.password}")
    private  String password;

    /**
     * 整合第三方bean
     * @return
     */
    @Bean("dataSource")//假如没有指定名字，默认为方法名
    @Lazy(false)
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driverClass);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
        return bean;
    }

    @Bean
    public SqlSessionTemplate sessionTemplate(SqlSessionFactoryBean sessionFactoryBean) throws Exception {
        SqlSessionTemplate sessionTemplate = new SqlSessionTemplate(sessionFactoryBean.getObject());
        return sessionTemplate;
    }
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource());
        return transactionManager;
    }
}
